<template>
	<view class="page-style">
		<button @click="read">读取</button>
		<button @click="save">保存</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {

			};
		},
		methods: {
			// 读取本地json文件
			readLocalJson(path) {
				return new Promise((resolve, reject) => {
					plus.io.resolveLocalFileSystemURL(path, entry => {
						entry.file(file => {
							console.log(file, 'file')
							const reader = new plus.io.FileReader();
							reader.onloadend = evt => {
								resolve(JSON.parse(evt.target.result))
							};
							reader.onerror = error => reject(error);
							reader.readAsText(file, 'utf-8');
						}, reject);
					}, reject);
				});
			},
			read() {
				// 'static/dev.json'
				// plus.io.convertLocalFileSystemURL('_doc/') + "data.json"
				// plus.io.convertLocalFileSystemURL('_doc/') + "static/dev.json"
				// console.log(plus.io.convertLocalFileSystemURL('_www/') + "static/dev.json", '读取路径')
				// plus.io.convertLocalFileSystemURL('_doc/') + 
				// /storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/www/static/dev.json"

				const path = plus.io.convertLocalFileSystemURL('_www/') + "static/dev.json";
				this.readLocalJson(path).then(data => {
					console.log(data);
				}).catch(err => {
					console.error('读取失败', err);
				});
			},
			// 保存json到本地
			saveJsonWithPromise(jsonData, filePath = (plus.io.convertLocalFileSystemURL('_doc/') + 'data.json')) {
				// console.log(plus.io.convertLocalFileSystemURL('_doc/') + 'data.json', '保存路径')
				return new Promise((resolve, reject) => {
					const jsonString = JSON.stringify(jsonData, null, 2);
					plus.io.resolveLocalFileSystemURL(filePath,
						(entry) => {
							// console.log(filePath, 'filePath')
							entry.createWriter((writer) => {
								writer.write(jsonString);
								resolve({
									path: entry.fullPath
								});

							}, reject);
						}, () => {
							// console.log('进入2', plus.io.PUBLIC_DOWNLOADS)
							// console.log(plus.io.convertLocalFileSystemURL('_doc/'), '保存路径')
							plus.io.resolveLocalFileSystemURL(plus.io.convertLocalFileSystemURL('_doc/'),
								(dirEntry) => {
									dirEntry.getFile(filePath.split('/').pop(), {
										create: true
									}, (fileEntry) => {
										fileEntry.createWriter((writer) => {
											writer.write(jsonString);
											resolve({
												path: fileEntry.fullPath
											});
										}, reject);
									}, reject);
								}, reject
							);
						}
					);
				});
			},
			save() {
				this.saveJsonWithPromise({
					key: 'value' //内容
				}).then(res => console.log('保存成功:', res.path)).catch(err => console.error('失败:', err));
			}

		}
	}
</script>

<style lang="scss">

</style>